package com.imyuanma.qingyun.fs.util;

import com.imyuanma.qingyun.common.client.ums.LoginUserHolder;
import com.imyuanma.qingyun.common.util.StringUtil;
import com.imyuanma.qingyun.fs.model.FsFile;
import com.imyuanma.qingyun.fs.model.enums.EFsFileStatusEnum;
import com.imyuanma.qingyun.fs.model.enums.EFsFileTypeEnum;
import com.imyuanma.qingyun.fs.model.enums.EFsMediaType;
import com.imyuanma.qingyun.interfaces.ums.model.LoginUserDTO;
import org.springframework.web.multipart.MultipartFile;

import java.util.Calendar;

/**
 * 文件服务工厂对象
 *
 * @author wangjy
 * @date 2022/07/24 12:08:02
 */
public class FsModelFactory {
    /**
     * 构建文件信息
     *
     * @param file
     * @param folder
     * @param businessCode
     * @return
     */
    public static FsFile buildFsFile(MultipartFile file, FsFile folder, String businessCode) {
        // 文件名
        String fileName = file.getOriginalFilename();
        // 后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uuid = StringUtil.getUUID();
        // 重写文件名, 实际存储时名字, 避免重名/不合规等问题
        String rewriteName = uuid + suffix;
        Calendar c = Calendar.getInstance();

        // 文件持久化目录, url
        FsFile fsFile = new FsFile();
        fsFile.setId(uuid);
        fsFile.setName(fileName);
        fsFile.setSaveName(rewriteName);
        fsFile.setStatus(EFsFileStatusEnum.NORMAL.getCode());
//        fsFile.setRemark();
        fsFile.setMediaType(EFsMediaType.ofSuffix(suffix).getCode());
        fsFile.setFolderId(folder.getId());
        fsFile.setFileSize(file.getSize());
        fsFile.setFileType(EFsFileTypeEnum.FILE.getCode());
        fsFile.setAddr(String.format("%s/%s/%s/%s/%s", folder.getAddr(), c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), rewriteName));
        fsFile.setPath(String.format("%s/%s/%s/%s/%s", folder.getPath(), c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), rewriteName));
        fsFile.setBusinessCode(businessCode);
        LoginUserDTO loginUserDTO = LoginUserHolder.getLoginUser();
        if (loginUserDTO != null) {
            fsFile.setCreateUserId(loginUserDTO.getUserId());
            fsFile.setUpdateUserId(loginUserDTO.getUserId());
        }
        return fsFile;
    }
}
